package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Log4j2
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getReportService(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverReportList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime dateMax = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime dateMin = LocalDateTime.of(date, LocalTime.MIN);

            Map map = new HashMap();
            map.put("begin", dateMin);
            map.put("end", dateMax);
            map.put("status", Orders.COMPLETED);
            Double turnOver = orderMapper.getStatistics(map);
            turnOver = turnOver == null ? 0.0 : turnOver;
            turnoverReportList.add(turnOver);
        }


        return TurnoverReportVO.builder().dateList(org.apache.commons.lang3.StringUtils.join(dateList, ",")).turnoverList(org.apache.commons.lang3.StringUtils.join(turnoverReportList, ",")).build();
    }

    @Override
    public SalesTop10ReportVO getReportTop(LocalDate begin, LocalDate end) {
        LocalDateTime dateMin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime dateMax = LocalDateTime.of(end, LocalTime.MAX);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();


        Map map = new HashMap();
        map.put("begin", dateMin);
        map.put("end", dateMax);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> turnOver = orderMapper.getSalesTop10(map);
        turnOver.forEach(item -> {
            nameList.add(item.getName());
            numberList.add(item.getNumber());
        });
//        turnOver.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
//        turnOver.stream().map(GoodsSalesDTO -> GoodsSalesDTO.getName()).collect(Collectors.toList());

        System.out.println(turnOver);
//            nameList.add(turnOver);

        return SalesTop10ReportVO.builder().nameList(StringUtils.join(nameList, ",")).numberList(StringUtils.join(numberList, ",")).build();
    }

    @Override
    public UserReportVO getUserReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime dateMin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime dateMax = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", dateMax);
            Integer userTotalCount = userMapper.getUserReport(map);
            totalUserList.add(userTotalCount);
            map.put("begin", dateMin);
            Integer userCreateCount = userMapper.getUserReport(map);
            newUserList.add(userCreateCount);
        }


        return UserReportVO.builder().dateList(StringUtils.join(dateList, ",")).newUserList(StringUtils.join(newUserList, ",")).totalUserList(StringUtils.join(totalUserList, ",")).build();
    }

    @Override
    public OrderReportVO getOrderReportVO(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);
            map.put("begin", beginTime);
            Integer count = orderMapper.getOrdersStatistics(map);
            log.info("count数量：{}", count);
            orderCountList.add(count);
            map.put("status", Orders.COMPLETED);
            Integer completionCount = orderMapper.getOrdersStatistics(map);
            validOrderCountList.add(completionCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }

        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();

    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        InputStream resource = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel =  new XSSFWorkbook(resource);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间" + beginDate + "至" + endDate);
            sheet.getRow(3).getCell(2).setCellValue(data.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(data.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(data.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(data.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(data.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO dt = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(String.valueOf(date));
                row.getCell(2).setCellValue(dt.getTurnover());
                row.getCell(3).setCellValue(dt.getValidOrderCount());
                row.getCell(4).setCellValue(dt.getOrderCompletionRate());
                row.getCell(5).setCellValue(dt.getUnitPrice());
                row.getCell(6).setCellValue(dt.getNewUsers());
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            excel.close();
            resource.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
